package com.yonghui.springsecurityoauth2demo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class GrantedAuthoritySetTypeHandler extends BaseTypeHandler<Set<SimpleGrantedAuthority>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<SimpleGrantedAuthority> parameter, JdbcType jdbcType) throws SQLException {
        // 将 Set<SimpleGrantedAuthority> 转换为逗号分隔的字符串，然后设置到 PreparedStatement 中
        StringBuilder builder = new StringBuilder();
        for (SimpleGrantedAuthority authority : parameter) {
            builder.append(authority.getAuthority()).append(",");
        }
        String authorities = builder.toString();
        if (authorities.length() > 0) {
            authorities = authorities.substring(0, authorities.length() - 1); // 移除最后一个逗号
        }
        ps.setString(i, authorities);
    }

    @Override
    public Set<SimpleGrantedAuthority> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return convertToAuthorities(rs.getString(columnName));
    }

    @Override
    public Set<SimpleGrantedAuthority> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return convertToAuthorities(rs.getString(columnIndex));
    }

    @Override
    public Set<SimpleGrantedAuthority> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return convertToAuthorities(cs.getString(columnIndex));
    }

    private Set<SimpleGrantedAuthority> convertToAuthorities(String authoritiesString) {
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        if (authoritiesString != null && !authoritiesString.isEmpty()) {
            String[] authorityArray = authoritiesString.split(",");
            for (String authority : authorityArray) {
                authorities.add(new SimpleGrantedAuthority(authority));
            }
        }
        return authorities;
    }
}
